import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { 
  Card, 
  List, 
  Avatar, 
  Tag, 
  Button, 
  Input, 
  Select, 
  Space, 
  Pagination,
  Empty,
  Spin,
  Row,
  Col,
  Tabs
} from 'antd';
import { 
  BookOutlined, 
  PlusOutlined, 
  SearchOutlined,
  EyeOutlined,
  LikeOutlined,
  ClockCircleOutlined,
  FileTextOutlined,
  DownloadOutlined
} from '@ant-design/icons';
import { Knowledge } from '../../types';
import './Knowledge.scss';

const { Search } = Input;
const { Option } = Select;
const { TabPane } = Tabs;

const Knowledge: React.FC = () => {
  const navigate = useNavigate();
  const [loading, setLoading] = useState(false);
  const [knowledge, setKnowledge] = useState<Knowledge[]>([]);
  const [currentPage, setCurrentPage] = useState(1);
  const [total, setTotal] = useState(0);
  const [searchKeyword, setSearchKeyword] = useState('');
  const [categoryFilter, setCategoryFilter] = useState('all');
  const [sortBy, setSortBy] = useState('latest');

  // 模拟数据
  const mockKnowledge: Knowledge[] = [
    {
      id: '1',
      title: 'React Hooks 完全指南',
      content: '详细介绍React Hooks的使用方法和最佳实践...',
      author: { id: '1', username: '张老师', email: 'zhang@university.edu', role: 'teacher' },
      category: '前端开发',
      tags: ['React', 'Hooks', 'JavaScript'],
      createdAt: '2024-01-15T10:00:00Z',
      updatedAt: '2024-01-15T10:00:00Z',
      views: 1256,
      likes: 89,
    },
    {
      id: '2',
      title: '数据结构与算法基础',
      content: '从基础数据结构到高级算法的完整学习路径...',
      author: { id: '2', username: '李教授', email: 'li@university.edu', role: 'teacher' },
      category: '计算机基础',
      tags: ['数据结构', '算法', '编程'],
      createdAt: '2024-01-14T14:30:00Z',
      updatedAt: '2024-01-14T14:30:00Z',
      views: 2341,
      likes: 156,
    },
    {
      id: '3',
      title: 'Python 数据分析实战',
      content: '使用Python进行数据分析的完整教程...',
      author: { id: '3', username: '王老师', email: 'wang@university.edu', role: 'teacher' },
      category: '数据分析',
      tags: ['Python', '数据分析', 'Pandas'],
      createdAt: '2024-01-13T09:15:00Z',
      updatedAt: '2024-01-13T09:15:00Z',
      views: 1890,
      likes: 123,
    },
    {
      id: '4',
      title: '机器学习入门教程',
      content: '机器学习基础概念和常用算法介绍...',
      author: { id: '4', username: '陈博士', email: 'chen@university.edu', role: 'teacher' },
      category: '人工智能',
      tags: ['机器学习', 'AI', '算法'],
      createdAt: '2024-01-12T16:45:00Z',
      updatedAt: '2024-01-12T16:45:00Z',
      views: 3456,
      likes: 234,
    },
    {
      id: '5',
      title: '数据库设计原则',
      content: '关系型数据库设计的最佳实践和规范...',
      author: { id: '5', username: '刘老师', email: 'liu@university.edu', role: 'teacher' },
      category: '数据库',
      tags: ['数据库', 'SQL', '设计'],
      createdAt: '2024-01-11T11:20:00Z',
      updatedAt: '2024-01-11T11:20:00Z',
      views: 987,
      likes: 67,
    },
  ];

  const categories = [
    { value: 'all', label: '全部分类' },
    { value: '前端开发', label: '前端开发' },
    { value: '计算机基础', label: '计算机基础' },
    { value: '数据分析', label: '数据分析' },
    { value: '人工智能', label: '人工智能' },
    { value: '数据库', label: '数据库' },
  ];

  useEffect(() => {
    loadKnowledge();
  }, [currentPage, searchKeyword, categoryFilter, sortBy]);

  const loadKnowledge = async () => {
    setLoading(true);
    try {
      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 500));
      
      let filteredKnowledge = mockKnowledge;
      
      // 按分类过滤
      if (categoryFilter !== 'all') {
        filteredKnowledge = mockKnowledge.filter(item => item.category === categoryFilter);
      }
      
      // 按关键词搜索
      if (searchKeyword) {
        filteredKnowledge = filteredKnowledge.filter(item => 
          item.title.includes(searchKeyword) || 
          item.content.includes(searchKeyword) ||
          item.tags.some(tag => tag.includes(searchKeyword))
        );
      }
      
      // 排序
      filteredKnowledge.sort((a, b) => {
        switch (sortBy) {
          case 'latest':
            return new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime();
          case 'popular':
            return b.views - a.views;
          case 'likes':
            return b.likes - a.likes;
          default:
            return 0;
        }
      });
      
      setKnowledge(filteredKnowledge);
      setTotal(filteredKnowledge.length);
    } catch (error) {
      console.error('加载知识库失败:', error);
    } finally {
      setLoading(false);
    }
  };

  const handleKnowledgeClick = (knowledgeId: string) => {
    navigate(`/knowledge/${knowledgeId}`);
  };

  const handleCreateKnowledge = () => {
    navigate('/knowledge/create');
  };

  const handleDownload = (knowledgeId: string, e: React.MouseEvent) => {
    e.stopPropagation();
    // 处理下载逻辑
    console.log('下载知识库:', knowledgeId);
  };

  const handleSearch = (value: string) => {
    setSearchKeyword(value);
    setCurrentPage(1);
  };

  const handleCategoryChange = (value: string) => {
    setCategoryFilter(value);
    setCurrentPage(1);
  };

  const handleSortChange = (value: string) => {
    setSortBy(value);
    setCurrentPage(1);
  };

  const getCategoryColor = (category: string) => {
    const colors = {
      '前端开发': 'blue',
      '计算机基础': 'green',
      '数据分析': 'orange',
      '人工智能': 'purple',
      '数据库': 'red',
    };
    return colors[category as keyof typeof colors] || 'default';
  };

  const formatDate = (dateString: string) => {
    const date = new Date(dateString);
    const now = new Date();
    const diff = now.getTime() - date.getTime();
    const days = Math.floor(diff / (1000 * 60 * 60 * 24));
    
    if (days === 0) {
      return '今天';
    } else if (days === 1) {
      return '昨天';
    } else if (days < 7) {
      return `${days}天前`;
    } else {
      return date.toLocaleDateString();
    }
  };

  return (
    <div className="knowledge-page">
      <div className="page-header">
        <div className="header-left">
          <h1>知识库</h1>
          <p>学习资源，知识分享，共同进步</p>
        </div>
        <div className="header-right">
          <Button 
            type="primary" 
            icon={<PlusOutlined />}
            onClick={handleCreateKnowledge}
          >
            分享知识
          </Button>
        </div>
      </div>

      {/* 分类标签 */}
      <Card className="category-card">
        <Tabs 
          activeKey={categoryFilter} 
          onChange={handleCategoryChange}
          items={categories.map(cat => ({
            key: cat.value,
            label: cat.label,
          }))}
        />
      </Card>

      {/* 筛选和搜索 */}
      <Card className="filter-card">
        <div className="filter-content">
          <Space size="middle" wrap>
            <Search
              placeholder="搜索知识库..."
              allowClear
              onSearch={handleSearch}
              style={{ width: 300 }}
              prefix={<SearchOutlined />}
            />
            <Select
              value={sortBy}
              onChange={handleSortChange}
              style={{ width: 120 }}
            >
              <Option value="latest">最新发布</Option>
              <Option value="popular">最多浏览</Option>
              <Option value="likes">最多点赞</Option>
            </Select>
          </Space>
        </div>
      </Card>

      {/* 知识库列表 */}
      <Card className="knowledge-card">
        <Spin spinning={loading}>
          {knowledge.length > 0 ? (
            <List
              dataSource={knowledge}
              renderItem={(item) => (
                <List.Item
                  className="knowledge-item"
                  onClick={() => handleKnowledgeClick(item.id)}
                >
                  <List.Item.Meta
                    avatar={<Avatar icon={<BookOutlined />} />}
                    title={
                      <div className="knowledge-title">
                        <span>{item.title}</span>
                        <Tag color={getCategoryColor(item.category)}>
                          {item.category}
                        </Tag>
                      </div>
                    }
                    description={
                      <div className="knowledge-content">
                        <p className="knowledge-text">{item.content}</p>
                        <div className="knowledge-tags">
                          {item.tags.map((tag, index) => (
                            <Tag key={index} size="small">{tag}</Tag>
                          ))}
                        </div>
                        <div className="knowledge-meta">
                          <div className="knowledge-author">
                            <span>作者：{item.author.username}</span>
                            <span className="knowledge-time">
                              <ClockCircleOutlined /> {formatDate(item.createdAt)}
                            </span>
                          </div>
                          <div className="knowledge-stats">
                            <span><EyeOutlined /> {item.views}</span>
                            <span><LikeOutlined /> {item.likes}</span>
                            <Button 
                              type="text" 
                              size="small"
                              icon={<DownloadOutlined />}
                              onClick={(e) => handleDownload(item.id, e)}
                            >
                              下载
                            </Button>
                          </div>
                        </div>
                      </div>
                    }
                  />
                </List.Item>
              )}
            />
          ) : (
            <Empty 
              description="暂无知识库内容"
              image={Empty.PRESENTED_IMAGE_SIMPLE}
            />
          )}
        </Spin>
        
        {total > 0 && (
          <div className="pagination-wrapper">
            <Pagination
              current={currentPage}
              total={total}
              pageSize={10}
              onChange={setCurrentPage}
              showSizeChanger={false}
              showQuickJumper
              showTotal={(total, range) => 
                `第 ${range[0]}-${range[1]} 条，共 ${total} 条`
              }
            />
          </div>
        )}
      </Card>
    </div>
  );
};

export default Knowledge;
